package com.fs.service;

import com.fs.entity.TaskType;
import com.fs.repository.TaskRepository;
import com.fs.entity.ScheduledTask;
import com.fs.service.bo.task.BoTask;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.transaction.Transactional;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Validated
public class ScheduledTaskService {
    private final TaskRepository taskDao;
    public static final String NOTIFY = TaskType.Notify.name();
    public static final String CUT_POWER = TaskType.CutPower.name();

    public ScheduledTaskService(TaskRepository taskDao) {
        this.taskDao = taskDao;
    }


    public void addTask(String id, String taskType, @NotBlank String content) {
        if (!taskType.equals(NOTIFY) && !taskType.equals(CUT_POWER)) {
            throw new BadParamException();
        }
        ScheduledTask task = new ScheduledTask();
        task.setContent(content);
        task.setId(id);
        if (NOTIFY.equals(taskType)) {
            task.setType(TaskType.Notify);
        } else {
            task.setType(TaskType.CutPower);
        }
        taskDao.save(task);
    }

    public void removeTask(@NotNull String id) {
        taskDao.deleteById(id);
    }

    public List<BoTask> getTasks() {
        List<ScheduledTask> all = taskDao.findAll();
        return all.stream().map(BoTask::new).collect(Collectors.toList());
    }


}
